// 天地图密钥
const TOKEN = '72d5cb5710cf5292d787787ddc170069'

export class TiandituLayer {
  constructor() {
    // 随机使用t0-t7的服务器
    this.serverNum = Math.floor(Math.random() * 8)
  }

  // 获取完整的瓦片URL
  getTileUrl(baseUrl, layer) {
    return baseUrl + 
      '&SERVICE=WMTS' +
      '&REQUEST=GetTile' +
      '&VERSION=1.0.0' +
      '&LAYER=' + layer +
      '&STYLE=default' +
      '&TILEMATRIXSET=w' +
      '&TILEMATRIX={z}' +
      '&TILEROW={y}' +
      '&TILECOL={x}' +
      '&FORMAT=tiles'
  }

  // 创建栅格图层source
  createRasterSource(type) {
    const baseUrl = `http://t${this.serverNum}.tianditu.com/${type}_w/wmts?tk=${TOKEN}`
    return {
      type: 'raster',
      tiles: [this.getTileUrl(baseUrl, type)],
      tileSize: 256
    }
  }

  // 创建图层样式
  createLayerStyle(id, source) {
    return {
      id,
      type: 'raster',
      source
    }
  }

  // 获取电子地图样式
  getVectorStyle() {
    return {
      version: 8,
      sources: {
        tdtVec: this.createRasterSource('vec'),
        tdtCva: this.createRasterSource('cva')
      },
      layers: [
        this.createLayerStyle('tdtVec', 'tdtVec'),
        this.createLayerStyle('tdtCva', 'tdtCva')
      ]
    }
  }

  // 获取影像地图样式
  getImageStyle() {
    return {
      version: 8,
      sources: {
        imgTdt: this.createRasterSource('img'),
        ciaTdt: this.createRasterSource('cia')
      },
      layers: [
        this.createLayerStyle('imgTdt', 'imgTdt'),
        this.createLayerStyle('ciaTdt', 'ciaTdt')
      ]
    }
  }

  // 切换地图样式
  switchMapStyle(map, type) {
    const style = type === 'vec' ? this.getVectorStyle() : this.getImageStyle()
    map.setStyle(style)
  }
} 